# -*- coding: utf-8 -*-
"""
小说数据模型
"""

import json
import os
from typing import List, Dict, Any
from datetime import datetime

from .chapter import Chapter
from .character import Character


class Novel:
    """小说模型类"""
    
    def __init__(self, title: str = "", author: str = "", description: str = ""):
        self.title = title
        self.author = author
        self.description = description
        self.chapters: List[Chapter] = []
        self.characters: List[Character] = []
        self.created_at = datetime.now()
        self.updated_at = datetime.now()
        self.file_path: str = ""
    
    def add_chapter(self, title: str, content: str = "") -> Chapter:
        """添加章节"""
        chapter = Chapter(
            title=title,
            content=content,
            order=len(self.chapters) + 1
        )
        self.chapters.append(chapter)
        self.updated_at = datetime.now()
        return chapter
    
    def remove_chapter(self, chapter_id: str) -> bool:
        """删除章节"""
        for i, chapter in enumerate(self.chapters):
            if chapter.id == chapter_id:
                del self.chapters[i]
                # 重新排序
                for j, ch in enumerate(self.chapters):
                    ch.order = j + 1
                self.updated_at = datetime.now()
                return True
        return False
    
    def add_character(self, name: str) -> Character:
        """添加角色"""
        character = Character(name=name)
        self.characters.append(character)
        self.updated_at = datetime.now()
        return character
    
    def remove_character(self, character_id: str) -> bool:
        """删除角色"""
        for i, character in enumerate(self.characters):
            if character.id == character_id:
                del self.characters[i]
                self.updated_at = datetime.now()
                return True
        return False
    
    def get_total_word_count(self) -> int:
        """获取总字数"""
        return sum(chapter.get_word_count() for chapter in self.chapters)
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return {
            "title": self.title,
            "author": self.author,
            "description": self.description,
            "chapters": [chapter.to_dict() for chapter in self.chapters],
            "characters": [character.to_dict() for character in self.characters],
            "created_at": self.created_at.isoformat(),
            "updated_at": self.updated_at.isoformat(),
        }
    
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'Novel':
        """从字典创建实例"""
        novel = cls(
            title=data.get("title", ""),
            author=data.get("author", ""),
            description=data.get("description", "")
        )
        
        # 加载章节
        for chapter_data in data.get("chapters", []):
            chapter = Chapter.from_dict(chapter_data)
            novel.chapters.append(chapter)
        
        # 加载角色
        for character_data in data.get("characters", []):
            character = Character.from_dict(character_data)
            novel.characters.append(character)
        
        # 设置时间
        if "created_at" in data:
            novel.created_at = datetime.fromisoformat(data["created_at"])
        if "updated_at" in data:
            novel.updated_at = datetime.fromisoformat(data["updated_at"])
        
        return novel
    
    def save_to_file(self, file_path: str) -> bool:
        """保存到文件"""
        try:
            self.file_path = file_path
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(self.to_dict(), f, ensure_ascii=False, indent=2)
            return True
        except Exception as e:
            print(f"保存文件失败: {e}")
            return False
    
    @classmethod
    def load_from_file(cls, file_path: str) -> 'Novel':
        """从文件加载"""
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                data = json.load(f)
            novel = cls.from_dict(data)
            novel.file_path = file_path
            return novel
        except Exception as e:
            print(f"加载文件失败: {e}")
            return cls() 